package mynet

import (
	"fmt"
)

type msgHandler struct {
	router    map[int32]IRouter
	workSize  int
	taskQueue []chan IRequest
	wId       int
}

func (this *msgHandler) StartOneWork(workId int) {
	go func() {
		for {
			task := <-this.taskQueue[workId]
			this.DoHandler(task)
		}
	}()

}

func (this *msgHandler) StartWorkPool() {
	for i := 0; i < this.workSize; i++ {
		this.StartOneWork(i)
	}
}

func (this *msgHandler) SendTaskToWork(task IRequest) {
	this.taskQueue[this.wId] <- task
	this.wId = (this.wId + 1) % this.workSize
}

func (this *msgHandler) DoHandler(req IRequest) {
	task, ok := this.router[req.GetType()]
	if !ok {
		fmt.Println("msgId is not exist:", req.GetType())
		return
	}

	if !task.PreHandler(req) {
		return
	}
	if !task.Handler(req) {
		return
	}

	if !task.PostHandler(req) {
		return
	}
}

func (this *msgHandler) AddRouter(msgId int32, router IRouter) {
	_, ok := this.router[msgId]
	if ok {
		panic(string(fmt.Sprintf("this msgId is exist : %d", msgId)))
	}
	this.router[msgId] = router
}

func GetNewMsgHandler(workSize int) IMsgHandler {
	taskChan := make([]chan IRequest, workSize)
	for i := 0; i < len(taskChan); i++ {
		taskChan[i] = make(chan IRequest, 1024)
	}
	return &msgHandler{
		router:    make(map[int32]IRouter),
		wId:       0,
		workSize:  workSize,
		taskQueue: taskChan,
	}
}
